package com.lgy.web.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Arrays;
import java.util.List;

/**
 * Created by fengch on 2018-03-29.
 */
public class MyRealm extends AuthorizingRealm {
    @Override
    public void setName(String name) {
        super.setName("myRealm");
    }

    /**
     * shiro认证realm
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //用户传递的账号
        String username = (String) authenticationToken.getPrincipal();

        String password = "123456";  //假设从数据库中查的密码  111111加密散列的值


        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password, this.getName());

        return authenticationInfo;
    }

    /**
     * shiro 授权
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();

        //从数据库中查询所拥有的角色以及权限
        List<String> roles =  Arrays.asList("admin", "boss","user");
        List<String> permissions = Arrays.asList("user:add", "shop:update");

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(roles);
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }


}
